Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 fix: Nil pointer dereference with Must Bind binding #3171

Merged
merged 17 commits into from
Nov 25, 2024

Conversation

ItsMeSamey
Copy link
Contributor

if err is nil err.Error() panics
(eg. c.Bind().Must().JSON(...) successfully binds but panics

if err is nil err.Error() panics
(eg. c.Bind().Must().JSON(...) successfully binds but panics
@ItsMeSamey ItsMeSamey requested a review from a team as a code owner October 17, 2024 20:55
@ItsMeSamey ItsMeSamey requested review from gaby, sixcolors, ReneWerner87 and efectn and removed request for a team October 17, 2024 20:55
Copy link

welcome bot commented Oct 17, 2024

Thanks for opening this pull request! 🎉 Please check out our contributing guidelines. If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

Copy link
Contributor

coderabbitai bot commented Oct 17, 2024

Walkthrough

The changes involve updates to the Bind struct in the fiber package, specifically renaming the Must method to WithAutoHandling and the Should method to WithoutAutoHandling, along with modifications to their error handling logic. The returnErr method is simplified, and tests are updated to reflect these changes. Additionally, the README.md and API documentation are revised to provide clearer guidance on the new Binder feature and its functionalities, including updated examples and sections on validation.

Changes

File Change Summary
bind.go Renamed Must to WithAutoHandling, Should to WithoutAutoHandling, modified returnErr logic, and updated comments.
bind_test.go Added Test_returnErr, renamed Test_Bind_Must to Test_Bind_WithAutoHandling, updated tests.
binder/README.md Updated to reflect the new Binder feature and error handling changes, added new examples.
docs/api/bind.md Updated method signatures from Must to WithAutoHandling and Should to WithoutAutoHandling, added validation section and examples.
ctx.go Updated comments for clarity and changed field should to dontHandleErrs in Bind struct.

Possibly related PRs

Suggested labels

🧹 Updates, 📒 Documentation

Suggested reviewers

  • sixcolors
  • efectn
  • ReneWerner87

🐰 In the meadow, changes bloom,
With WithAutoHandling, there's less gloom.
Errors handled, tests refined,
A clearer path for all to find.
Documentation shines bright and new,
Hopping forward, we bid adieu! 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6e667d6 and 2a97898.

📒 Files selected for processing (1)
  • binder/README.md (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • binder/README.md

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@ItsMeSamey ItsMeSamey changed the title Fix nil pointer dereference with Must Bind binding error Fix nil pointer dereference with Must Bind binding Oct 17, 2024
@gaby
Copy link
Member

gaby commented Oct 18, 2024

@ItsMeSamey Anyway we could trigger this in a new unit-test?

@gaby gaby changed the title Fix nil pointer dereference with Must Bind binding 🐛 fix: Nil pointer dereference with Must Bind binding Oct 18, 2024
Copy link

codecov bot commented Oct 18, 2024

Codecov Report

Attention: Patch coverage is 80.00000% with 2 lines in your changes missing coverage. Please review.

Project coverage is 82.78%. Comparing base (f8b490f) to head (2a97898).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
bind.go 75.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3171      +/-   ##
==========================================
- Coverage   82.85%   82.78%   -0.08%     
==========================================
  Files         114      114              
  Lines       11189    11189              
==========================================
- Hits         9271     9263       -8     
- Misses       1520     1526       +6     
- Partials      398      400       +2     
Flag Coverage Δ
unittests 82.78% <80.00%> (-0.08%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.


🚨 Try these New Features:

make sure returnErr works with nil error
as in majority of cases we expect err to be nil, this should provide better short-cutting
@ItsMeSamey
Copy link
Contributor Author

@gaby I've added a test for this

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (1)
bind_test.go (1)

22-29: Approve the new test function with a suggestion.

The new Test_returnErr function is a good addition to test the fix for the nil pointer dereference issue. It correctly checks that no error is returned when a nil error is passed to returnErr.

To make the test more robust, consider adding an additional assertion to check the response status code:

 err := c.Bind().Must().returnErr(nil)
 require.Equal(t, nil, err)
+require.Equal(t, 200, c.Response().StatusCode())

This will ensure that not only is no error returned, but also that the response status remains unchanged when a nil error is passed.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0fa70ab and dde670f.

📒 Files selected for processing (2)
  • bind.go (1 hunks)
  • bind_test.go (1 hunks)
🧰 Additional context used
🔇 Additional comments (2)
bind_test.go (1)

Line range hint 1-1183: Overall approval of the test file.

The bind_test.go file appears to be well-structured and comprehensive, covering various binding scenarios including Query, Header, Body, URI, and Cookie bindings. The addition of the Test_returnErr function complements the existing test suite by addressing the specific issue mentioned in the PR.

The file also includes benchmark functions, which are valuable for monitoring performance. No significant issues or necessary improvements are identified in the rest of the file.

bind.go (1)

44-45: Properly handling nil errors to prevent nil pointer dereference

The updated condition if err == nil || b.should ensures that the function returns early when err is nil or b.should is true, preventing a nil pointer dereference when calling err.Error() later in the code. This change effectively fixes the panic issue described in the pull request.

bind.go Show resolved Hide resolved
bind.go Outdated Show resolved Hide resolved
@ItsMeSamey ItsMeSamey requested a review from gaby October 19, 2024 23:42
@ItsMeSamey
Copy link
Contributor Author

@gaby
I've been wondering why is Must() even needed, it only adds overhead so won't we be better off removing it altogether. Setting status should be user's job anyway
Should i open a discussion / issue about this?

@gaby
Copy link
Member

gaby commented Oct 21, 2024

@gaby I've been wondering why is Must() even needed, it only adds overhead so won't we be better off removing it altogether. Setting status should be user's job anyway Should i open a discussion / issue about this?

That's a question for @efectn

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
bind.go (1)

43-43: Update documentation for Custom binding

The comment "NOTE: Should/Must is still valid for Custom binders" above the Custom method is now outdated since Should/Must methods have been removed.

Remove or update the comment to reflect the new error handling approach.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b15eda0 and dde4c81.

📒 Files selected for processing (3)
  • bind.go (11 hunks)
  • bind_test.go (0 hunks)
  • ctx.go (0 hunks)
💤 Files with no reviewable changes (2)
  • bind_test.go
  • ctx.go
🧰 Additional context used
🔇 Additional comments (3)
bind.go (3)

52-52: LGTM: Consistent error handling pattern across all binding methods

The binding methods now follow a consistent and clean pattern:

  1. Call the appropriate binder
  2. Return any binding errors directly
  3. Validate the struct if binding succeeds

This simplification makes the error handling more predictable and allows users to handle status codes according to their needs.

Also applies to: 61-61, 71-71, 80-80, 89-89, 98-98, 107-107, 116-116, 125-125


147-147: LGTM: Clean error handling in Body binding

The Body binding method maintains a clean separation of concerns while consistently handling errors from custom binders. The direct error return aligns with the new error handling pattern.


22-22: Breaking Change: Removal of Must/Should chaining capability

The removal of the should field from the Bind struct is a breaking change that will affect existing code using the Must()/Should() chaining pattern. This change is necessary to fix the nil pointer dereference issue, but requires careful migration planning.

Consider documenting the migration path for users in the changelog, suggesting alternative error handling patterns such as:

if err := c.Bind().JSON(&data); err != nil {
    return err
}

@ReneWerner87
Copy link
Member

we will discuss this again internally and then let you know which way we want to go, thank you for your work and help

@ReneWerner87
Copy link
Member

here the last statement
#3178 (comment)

we want to rename the feature so that there is no confusion with the golang concept of MUST for panics

because the methods always return an error
the feature only ensures that the response is filled with it

Added a requested clarification
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
docs/api/bind.md (1)

461-468: Improve clarity and fix grammatical error

  1. Fix the grammatical error: "therefor" should be "therefore"
  2. Consider adding more details about error handling behavior
 ### WithAutoHandling
 
 If you want to handle binder errors automatically, you can use `WithAutoHandling`.  
 If there's an error, it will return the error and set HTTP status to `400 Bad Request`.
-This function does NOT panic therefor you must still return on error explicitly
+This function does NOT panic therefore you must still return on error explicitly. It safely handles
+all error cases, including nil errors.
 
 ```go title="Signature"
 func (b *Bind) WithAutoHandling() *Bind
🧰 Tools
🪛 LanguageTool

[grammar] ~465-~465: Did you mean to write ‘therefore’?
Context: ... Request`. This function does NOT panic therefor you must still return on error explicit...

(THEREFORE)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 080c001 and 0cfa1c8.

📒 Files selected for processing (1)
  • docs/api/bind.md (1 hunks)
🧰 Additional context used
🪛 LanguageTool
docs/api/bind.md

[grammar] ~465-~465: Did you mean to write ‘therefore’?
Context: ... Request`. This function does NOT panic therefor you must still return on error explicit...

(THEREFORE)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (7)
binder/README.md (4)

86-86: Clarify WithAutoHandlingWithStatus in the documentation

The section title mentions "WithAutoHandlingWithStatus", but this method is not explained or demonstrated in the documentation. Consider either:

  1. Adding documentation for WithAutoHandlingWithStatus, or
  2. Removing it from the title if it's not yet implemented

Line range hint 88-102: Improve documentation clarity and examples

Several improvements could enhance the documentation:

  1. The example uses GET with a request body, which is not a common RESTful practice. Consider using POST instead:
-app.Get("/", func(c fiber.Ctx) error {
+app.Post("/", func(c fiber.Ctx) error {
  1. Add an explicit example of the error response format:
// Error Response Example:
// {
//   "error": "Bad request: name is empty"
// }
  1. Clarify the automatic error handling behavior:
-If there's an error it'll return error and 400 as HTTP status.
+If there's a validation error or binding failure, it automatically sets a 400 HTTP status code and returns an error response.
  1. Document the nil error handling improvement:
// Note: WithAutoHandling safely handles nil errors during binding,
// preventing potential panics in the error handling chain.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~90-~90: A comma might be missing here.
Context: ...er WithAutoHandling(). If there's an error it'll return error and 400 as HTTP stat...

(AI_EN_LECTOR_MISSING_PUNCTUATION_COMMA)


[uncategorized] ~90-~90: The preposition “of” seems more likely in this position.
Context: ...d 400 as HTTP status. Here's an example for it: ```go // Field names should start ...

(AI_EN_LECTOR_REPLACEMENT_PREPOSITION)


102-102: Consider adding error handling examples

The example could be enhanced to show different error scenarios and their handling:

// Example 1: Missing required field
c.Bind().WithAutoHandling().JSON(p)
// Result: 400 Bad Request - "name is empty"

// Example 2: Invalid JSON
c.Bind().WithAutoHandling().JSON(p)
// Result: 400 Bad Request - "invalid JSON format"

// Example 3: Successful binding
c.Bind().WithAutoHandling().JSON(p)
// Result: Continues execution normally

Documentation needs update: WithAutoHandlingWithStatus method doesn't exist

The documentation in binder/README.md mentions "WithAutoHandling/WithAutoHandlingWithStatus" in its heading and content, but the codebase only implements WithAutoHandling(). The actual implementation shows that WithAutoHandling() sets the status code to 400 on error, making the separate "WithStatus" variant unnecessary or removed.

  • Remove references to "WithAutoHandlingWithStatus" from the documentation heading and content in binder/README.md
  • The rest of the documented behavior for WithAutoHandling() is accurate, including the 400 status code and error handling
🔗 Analysis chain

Line range hint 86-102: Verify documentation consistency with implementation

Let's ensure the documentation accurately reflects the implemented method names and behaviors.


Let me gather more specific information about the binding implementation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify method names and signatures in the codebase

# Check for old method names to ensure complete migration
echo "Checking for any remaining references to old method names..."
rg -i "Must\(\)" --type go
rg -i "Should\(\)" --type go

# Verify new method signatures
echo "Verifying new method signatures..."
ast-grep --pattern 'func $_(c *Ctx) Bind() *Bind {
  $$$
}'

# Check for any remaining references to WithAutoHandlingWithStatus
echo "Checking WithAutoHandlingWithStatus references..."
rg -i "WithAutoHandlingWithStatus"

Length of output: 553


Script:

#!/bin/bash
# Search for WithAutoHandling implementation and usage
echo "Checking WithAutoHandling implementation..."
rg -A 5 "WithAutoHandling"

# Search for binding-related structs and methods
echo "Checking Bind struct and methods..."
ast-grep --pattern 'type Bind struct {
  $$$
}'

# Look for actual binding implementation
echo "Looking for binding implementation..."
ast-grep --pattern 'func (b *Bind) JSON($_) error {
  $$$
}'

Length of output: 4003

🧰 Tools
🪛 LanguageTool

[uncategorized] ~90-~90: A comma might be missing here.
Context: ...er WithAutoHandling(). If there's an error it'll return error and 400 as HTTP stat...

(AI_EN_LECTOR_MISSING_PUNCTUATION_COMMA)


[uncategorized] ~90-~90: The preposition “of” seems more likely in this position.
Context: ...d 400 as HTTP status. Here's an example for it: ```go // Field names should start ...

(AI_EN_LECTOR_REPLACEMENT_PREPOSITION)

bind.go (2)

34-41: Consider enhancing the documentation

While the rename to WithAutoHandling is good, consider making the documentation more explicit about nil error handling to prevent future confusion.

- // If you want to handle binder errors automatically, you can use `WithAutoHandling`.  
- // If there's an error, it will return the error and set HTTP status to `400 Bad Request`.
- // You must still return on error explicitly
+ // WithAutoHandling configures automatic error handling for binding operations.
+ // When an error occurs:
+ // 1. Sets HTTP status to 400 Bad Request
+ // 2. Returns a formatted error message
+ // When no error occurs (nil error):
+ // 1. Returns nil without modifying the response
+ // Note: You must still handle the returned error in your code
🧰 Tools
🪛 golangci-lint

34-34: File is not goimports-ed

(goimports)


34-34: File is not gofumpt-ed with -extra

(gofumpt)


66-66: Fix typo in documentation

There's a typo in the note: "WithAutoHandling/WithAutoHandling" should be "WithAutoHandling/WithoutAutoHandling".

- // NOTE: WithAutoHandling/WithAutoHandling is still valid for Custom binders.
+ // NOTE: WithAutoHandling/WithoutAutoHandling is still valid for Custom binders.
docs/api/bind.md (1)

465-465: Fix grammar in documentation

There are two grammar issues in this line:

  1. "therefor" should be "therefore"
  2. Missing comma before "therefore"
-This function does NOT panic therefor you must still return on error explicitly
+This function does NOT panic, therefore you must still return on error explicitly
🧰 Tools
🪛 LanguageTool

[uncategorized] ~465-~465: Possible missing comma found.
Context: ...00 Bad Request`. This function does NOT panic therefor you must still return on error...

(AI_HYDRA_LEO_MISSING_COMMA)


[grammar] ~465-~465: Did you mean to write ‘therefore’?
Context: ... Request`. This function does NOT panic therefor you must still return on error explicit...

(THEREFORE)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0cfa1c8 and 8ec9427.

📒 Files selected for processing (4)
  • bind.go (3 hunks)
  • binder/README.md (2 hunks)
  • ctx.go (3 hunks)
  • docs/api/bind.md (1 hunks)
🧰 Additional context used
🪛 golangci-lint
bind.go

34-34: File is not goimports-ed

(goimports)


34-34: File is not gofumpt-ed with -extra

(gofumpt)

ctx.go

1863-1863: File is not gofumpt-ed with -extra

(gofumpt)


1863-1863: File is not goimports-ed

(goimports)

🪛 LanguageTool
docs/api/bind.md

[uncategorized] ~465-~465: Possible missing comma found.
Context: ...00 Bad Request`. This function does NOT panic therefor you must still return on error...

(AI_HYDRA_LEO_MISSING_COMMA)


[grammar] ~465-~465: Did you mean to write ‘therefore’?
Context: ... Request`. This function does NOT panic therefor you must still return on error explicit...

(THEREFORE)

🔇 Additional comments (7)
bind.go (5)

22-23: LGTM! Improved field naming

The rename from should to dontHandle better reflects the actual behavior of the flag and aligns with the new method names.


26-32: LGTM! Clear method naming and documentation

The rename to WithoutAutoHandling makes the behavior more explicit, and the documentation clearly indicates this is the default behavior.


43-46: LGTM! Nil error check fixes the reported issue

The condition err == nil || b.dontHandle correctly handles both nil errors and manual error handling mode.


49-50: Consider previous security feedback about error exposure

The previous review comment about not exposing internal error details to clients is still valid. Consider implementing that suggestion to improve security.


34-41: Verify all usages of renamed methods

Let's verify that all usages of the old method names (Must and Should) have been updated throughout the codebase.

✅ Verification successful

No issues found with method renaming

The codebase shows that WithAutoHandling() is correctly used in tests and there are no references to the old method names (Must and Should). The changes appear to be properly implemented with no remaining references to the old methods.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining references to the old method names
echo "Checking for old method names..."
rg -l "\.Must\(\)" --type go
rg -l "\.Should\(\)" --type go

# Search for new method names to confirm updates
echo "Verifying new method names..."
rg -l "\.WithAutoHandling\(\)" --type go
rg -l "\.WithoutAutoHandling\(\)" --type go

Length of output: 309


Script:

#!/bin/bash
# Let's check the actual usage context of these methods
echo "Checking WithAutoHandling usage context:"
rg "\.WithAutoHandling\(\)" -B 2 -A 2 --type go

echo -e "\nChecking test file content for better context:"
cat bind_test.go

Length of output: 47741

🧰 Tools
🪛 golangci-lint

34-34: File is not goimports-ed

(goimports)


34-34: File is not gofumpt-ed with -extra

(gofumpt)

docs/api/bind.md (2)

461-477: Add information about error handling improvements

The documentation should address the nil pointer dereference fix that motivated this change.

Add this explanation:

 If you want to handle binder errors automatically, you can use `WithAutoHandling`.  
-If there's an error, it will return the error and set HTTP status to `400 Bad Request`.
+If there's an error, it will return the error and set HTTP status to `400 Bad Request`. This method
+safely handles all error cases, including nil errors, preventing potential panics that could occur
+when using error handling methods.
+
+:::note
+This method replaces the previous `Must` method and includes improved error handling to prevent
+nil pointer dereference issues.
+:::
🧰 Tools
🪛 LanguageTool

[uncategorized] ~465-~465: Possible missing comma found.
Context: ...00 Bad Request`. This function does NOT panic therefor you must still return on error...

(AI_HYDRA_LEO_MISSING_COMMA)


[grammar] ~465-~465: Did you mean to write ‘therefore’?
Context: ... Request`. This function does NOT panic therefor you must still return on error explicit...

(THEREFORE)


461-477: LGTM! Clear documentation for the renamed methods

The documentation clearly explains the purpose and behavior of both WithAutoHandling and WithoutAutoHandling methods, maintaining consistency with the code changes.

🧰 Tools
🪛 LanguageTool

[uncategorized] ~465-~465: Possible missing comma found.
Context: ...00 Bad Request`. This function does NOT panic therefor you must still return on error...

(AI_HYDRA_LEO_MISSING_COMMA)


[grammar] ~465-~465: Did you mean to write ‘therefore’?
Context: ... Request`. This function does NOT panic therefor you must still return on error explicit...

(THEREFORE)

bind.go Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (3)
bind.go (2)

34-37: Enhance documentation for clarity

While the documentation is good, consider adding examples to illustrate proper usage, especially regarding the note about explicit error returns.

Example addition:

 // If you want to handle binder errors automatically, you can use `WithAutoHandling`.  
 // If there's an error, it will return the error and set HTTP status to `400 Bad Request`.
 // You must still return on error explicitly
+//
+// Example:
+//  if err := c.Bind().WithAutoHandling().JSON(&data); err != nil {
+//    return err // Required: must explicitly return the error
+//  }
🧰 Tools
🪛 golangci-lint (1.61.0)

34-34: File is not gofumpt-ed with -extra

(gofumpt)


66-66: Fix typo in documentation

There's a typo in the comment:

-// NOTE: WithAutoHandling/WithAutoHandling is still valid for Custom binders.
+// NOTE: WithAutoHandling/WithoutAutoHandling is still valid for Custom binders.
ctx.go (1)

1863-1864: Field rename looks good, but fix formatting

The rename from should to dontHandleErrs improves clarity and aligns with the nil pointer dereference fix. However, there's a minor formatting issue.

Fix the extra spaces after the colon:

-			ctx       : c,
-			dontHandleErrs: true,
+			ctx: c,
+			dontHandleErrs: true,
🧰 Tools
🪛 golangci-lint (1.61.0)

1863-1863: File is not gofumpt-ed with -extra

(gofumpt)


1863-1863: File is not goimports-ed

(goimports)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8ec9427 and 5697339.

📒 Files selected for processing (2)
  • bind.go (3 hunks)
  • ctx.go (3 hunks)
🧰 Additional context used
🪛 golangci-lint (1.61.0)
bind.go

22-22: File is not goimports-ed

(goimports)


22-22: File is not gofumpt-ed with -extra

(gofumpt)


34-34: File is not gofumpt-ed with -extra

(gofumpt)

ctx.go

1863-1863: File is not gofumpt-ed with -extra

(gofumpt)


1863-1863: File is not goimports-ed

(goimports)

🔇 Additional comments (5)
bind.go (4)

22-23: LGTM: Field rename improves clarity

The rename from should to dontHandleErrs better communicates the field's purpose and aligns with the new method names.

🧰 Tools
🪛 golangci-lint (1.61.0)

22-22: File is not goimports-ed

(goimports)


22-22: File is not gofumpt-ed with -extra

(gofumpt)


43-46: LGTM: Proper nil check prevents panic

The nil check before accessing the error properly fixes the nil pointer dereference issue.


49-50: ⚠️ Potential issue

Security: Avoid exposing internal error details

The current implementation exposes internal error details to clients, which could leak sensitive information.

Consider implementing a more secure error handling approach:

 b.ctx.Status(StatusBadRequest)
-return NewError(StatusBadRequest, "Bad request: "+err.Error())
+// Log the detailed error for debugging
+b.ctx.App().Logger().Error(err)
+// Return a generic error message to the client
+return NewError(StatusBadRequest, "Invalid request format")

28-40: Verify method rename impact

Let's verify that all call sites have been updated to use the new method names.

✅ Verification successful

Based on the analysis of the shell script results, I can now generate the final response:

Method rename impact verified successfully

The codebase shows proper adoption of the new method names:

  • WithAutoHandling() is used in tests and properly tested for error handling
  • No instances of old method names (Must() or Should()) were found
  • The new methods are well documented and have proper test coverage
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining usage of old method names
echo "Checking for old method names..."
rg -l "\.Must\(\)" --type go
rg -l "\.Should\(\)" --type go

# Search for usage of new method names to ensure proper adoption
echo "Checking new method usage..."
rg -l "\.WithAutoHandling\(\)" --type go
rg -l "\.WithoutAutoHandling\(\)" --type go

Length of output: 307


Script:

#!/bin/bash
# Let's check the actual usage context of these methods
echo "Checking WithAutoHandling usage context..."
rg "\.WithAutoHandling\(\)" -B 2 -A 2 --type go

echo "Checking if there are any other similar method patterns in bind.go..."
rg "func.*Bind.*\)" bind.go

# Let's also check test coverage to ensure the new methods are properly tested
echo "Checking test coverage..."
cat bind_test.go

Length of output: 48495

🧰 Tools
🪛 golangci-lint (1.61.0)

34-34: File is not gofumpt-ed with -extra

(gofumpt)

ctx.go (1)

643-643: Documentation improvement looks good!

The added comment clarifies that the function is generic and can handle different header types, which improves code maintainability.

@ReneWerner87
Copy link
Member

Thx

@ReneWerner87
Copy link
Member

@ItsMeSamey pls fix the lint errors

image

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
bind.go (1)

66-66: Fix typo in documentation.

The comment has a duplicate "WithAutoHandling". It should be "WithAutoHandling/WithoutAutoHandling".

-// NOTE: WithAutoHandling/WithAutoHandling is still valid for Custom binders.
+// NOTE: WithAutoHandling/WithoutAutoHandling is still valid for Custom binders.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5697339 and 0b6b035.

📒 Files selected for processing (2)
  • bind.go (3 hunks)
  • ctx.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • ctx.go
🔇 Additional comments (4)
bind.go (4)

26-41: LGTM! Method renames improve API clarity.

The renames from Should()/Must() to WithoutAutoHandling()/WithAutoHandling() are excellent improvements:

  • More descriptive of their actual behavior
  • Removes confusion with Go's Must convention for panics
  • Clear documentation explaining the purpose

43-51: ⚠️ Potential issue

Fix addresses nil pointer but retains security concern.

The nil check at line 45 correctly fixes the nil pointer dereference. However, as noted in the previous review, exposing raw error messages to clients remains a security concern.

Consider this safer implementation:

 func (b *Bind) returnErr(err error) error {
 	if err == nil || b.dontHandleErrs {
 		return err
 	}
 
 	b.ctx.Status(StatusBadRequest)
-	return NewError(StatusBadRequest, "Bad request: "+err.Error())
+	b.ctx.App().Logger().Error(err)
+	return NewError(StatusBadRequest, "Invalid request format")
 }

28-38: Verify migration of existing code.

Since this is a breaking change that renames public methods, we should verify that all existing code has been updated.

✅ Verification successful

Let me check the actual content of these files to see if they contain the old method names or just the words "Must" or "Should" in different contexts.


Breaking changes have been properly migrated

The verification shows that:

  1. No instances of the old method names .Must() or .Should() exist in the codebase
  2. The new methods WithAutoHandling and WithoutAutoHandling are properly documented and used consistently in:
    • Main implementation (bind.go)
    • Tests (bind_test.go)
    • Documentation (docs/api/bind.md, binder/README.md)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining references to old method names
echo "Checking for old method names..."
rg -i "\.Must\(\)" || echo "No .Must() calls found"
rg -i "\.Should\(\)" || echo "No .Should() calls found"

# Search for examples and tests that might need updating
echo "Checking for potential test files..."
fd -e test.go | xargs rg -l "Must|Should"

Length of output: 601


Script:

#!/bin/bash
# Check the actual content of files that matched
echo "Checking content of matched files..."
for file in app_test.go ctx.go path.go middleware/rewrite/rewrite.go middleware/redirect/redirect.go middleware/adaptor/adaptor_test.go ctx_test.go client/request_test.go binder/mapping.go client/hooks.go; do
    if [ -f "$file" ]; then
        echo "=== $file ==="
        rg -C 2 "\.Must\(\)|\.Should\(\)" "$file" || echo "No exact method calls found"
    fi
done

# Also check for any WithoutAutoHandling or WithAutoHandling usage
echo -e "\nChecking for new method usage..."
rg "WithoutAutoHandling|WithAutoHandling"

Length of output: 5845


22-23: LGTM! Field rename improves clarity.

The rename from should to dontHandleErrs better describes the field's purpose. However, since this inverts the boolean logic, we should verify all usages.

✅ Verification successful

Field rename improves clarity and maintains correct error handling logic

The rename from should to dontHandleErrs is verified to be correctly implemented. The field is used consistently throughout the codebase:

  • WithoutAutoHandling() sets it to true (default behavior)
  • WithAutoHandling() sets it to false
  • returnErr() method correctly checks if err == nil || b.dontHandleErrs to determine whether to return raw error or handle it with 400 status

The boolean logic is properly inverted and all usages are consistent with the new name's semantics.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify all usages of the new field name and ensure correct boolean logic
ast-grep --pattern 'dontHandleErrs'

Length of output: 72


Script:

#!/bin/bash
# Let's check the usage context of dontHandleErrs more thoroughly
rg "dontHandleErrs" -B 3 -A 3

# Also check for the old field name 'should' to compare the logic
rg "should" -B 3 -A 3 --type go

# Let's also see the full Bind struct definition
ast-grep --pattern 'type Bind struct {
  $$$
}'

Length of output: 95306


Script:

#!/bin/bash
# Let's check the methods that use dontHandleErrs to verify the logic
ast-grep --pattern 'func ($b *Bind) $$$() $$ {
  $$$
  dontHandleErrs
  $$$
}'

# Also check for any error handling related methods
rg "returnErr" -A 5 -B 5

Length of output: 4980

@ItsMeSamey
Copy link
Contributor Author

@gaby
I believe this is ready to be merged now

Copy link
Member

@gaby gaby left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 LGTM

@gaby
Copy link
Member

gaby commented Nov 25, 2024

@ReneWerner87 @efectn Please check my changes to the README.md, if all good then we can merge it.

@ReneWerner87 ReneWerner87 merged commit f08ebf4 into gofiber:main Nov 25, 2024
15 of 18 checks passed
Copy link

welcome bot commented Nov 25, 2024

Congrats on merging your first pull request! 🎉 We here at Fiber are proud of you! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

4 participants